//
//  AppDelegate.m
//  Focus_Time
//
//  Created by MitnickKevin on 16/4/11.
//  Copyright © 2016年 SWUST. All rights reserved.
//

#import "AppDelegate.h"
#import "ZHYMainCollectionController.h"



//弱引用
#define WeakSelf(weakSelf)  __weak __typeof(&*self)weakSelf = self;
//颜色：
#define NTColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]

//控制器包含：
#import "MacauViewController.h"
#import "LoadingController.h"

//AVOS
#import <AVOSCloud/AVOSCloud.h>
#define APP_ID @"hMhbWtmfuYsk7lMYVKY56xGB-gzGzoHsz"
#define APP_KEY @"pUw2wTydkIFhoSN65gwNXCB1"
#define MASTER_KEY @"Uz3cpBpURanebykjy4JuwkkI"


//查看方法执行了多久：
#define BEGIN_RECORD   NSDate *startTime = [NSDate date];
#define END_RECORD     -[startTime timeIntervalSinceNow]
#define TotalShowingTime 1.5
#define JUDGE_TIME     if(END_RECORD < TotalShowingTime){sleep(TotalShowingTime - END_RECORD);}



//JPUSH
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件
#import <AdSupport/AdSupport.h>



//有关AVOS的一些宏：
#define Table_Name @"Table_Name"
#define Http_Url @"HttpUrl"
#define isToFit @"isToFit"
#define IP_Table_Name @"ipModel"
#define Jpush_AppKey @"JpushAppKey"



@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate
{
    NSString * _requestUrl;
    BOOL _isToFit;
    NSString * _Jpush_app_personal_key;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [AVOSCloud setApplicationId:APP_ID clientKey:APP_KEY];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    
//            AVObject *product = [AVObject objectWithClassName:Table_Name];
//            [product setObject:@"https://www.baidu.com" forKey:Http_Url];
//            [product setObject:@"1" forKey:isToFit];
//            [product setObject:@"d610d59d053bf22eb3069732" forKey:Jpush_AppKey];
//    
//            [product saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//                if (succeeded) {
//                    NSLog(@"====success");
//                } else {
//                    NSLog(@"保存新物品出错 %@", error);
//                }
//            }];
    
    LoadingController * loadingVC = [[LoadingController alloc]init];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = loadingVC;
    
    [self httpForAvosOptions:launchOptions];
    
    return YES;
    
}


-(void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}



- (BOOL)httpForAvosOptions:(NSDictionary *)launchOptions{
    
    WeakSelf(weakself)
    
    //取
    AVQuery *query = [AVQuery queryWithClassName:Table_Name];
    BEGIN_RECORD
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        JUDGE_TIME
        if (objects.count>0) {
            AVObject * obj = objects[0];
            NSString * urlStr = [obj objectForKey:Http_Url];
            _isToFit = [[obj objectForKey:isToFit] isEqualToString:@"1"];
            _Jpush_app_personal_key = [obj objectForKey:Jpush_AppKey];
            if (_Jpush_app_personal_key.length > 0) {
                [self registerJpushOptions:launchOptions];//显示webview的时候才注册推送。
            }
            
            if (urlStr.length == 0) {
                [weakself showTrueView];
            }
            else{
                _requestUrl = urlStr;
                [weakself showMacauViewIsToFit:_isToFit];
            }
        }
        if (error) {
            [self showTrueView];
        }
    }];
    return YES;
}


-(void)showTrueView
{
    self.window.rootViewController = [[ZHYMainCollectionController alloc] init];
    
    [self.window makeKeyAndVisible];

}

- (void)showMacauViewIsToFit:(BOOL)isFit
{
    MacauViewController* vc = [[MacauViewController alloc]init];
    vc.requestUrl = _requestUrl;
    self.window.rootViewController = vc;
    
    [self.window makeKeyAndVisible];
}
-(void)registerJpushOptions:(NSDictionary *)launchOptions
{
    //这里可能会需要分系统版本不同来设置🐟
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    //声明:app_key
    [JPUSHService setupWithOption:launchOptions appKey:_Jpush_app_personal_key channel:@"app store" apsForProduction:YES advertisingIdentifier:nil];
    
    //获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    // 注册通知,获取前台接收自定义消息。
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
}


//1、JPUSH--注册APNS 并上传deviceToken
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    //这里可以通过调接口将deviceToken传到服务器上去。
    
}

//1-1、注册失败的接口
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
//2-1、当应用在前台时收到通知时：
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    NSLog(@"iOS10收到推送: %@", [userInfo[@"aps"] objectForKey:@"alert"]);
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}
//2-2、程序关闭后, 通过点击推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    NSLog(@"iOS10点击推送%@", [userInfo[@"aps"] objectForKey:@"alert"]);
    completionHandler(UNNotificationPresentationOptionAlert);  // 系统要求执行这个方法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


#pragma mark 前台接收自定义消息的时候;
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    //    NSString *title = [userInfo valueForKey:@"title"];
    //    NSString *content = [userInfo valueForKey:@"content"];
    //    NSDictionary *extra = [userInfo valueForKey:@"extras"];
    
}


@end
